package com.softtown.modules.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softtown.common.enums.*;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;
import com.softtown.common.service.impl.BaseServiceImpl;
import com.softtown.common.utils.ConvertUtils;
import com.softtown.common.utils.Result;
import com.softtown.modules.message.service.SysEmailService;
import com.softtown.modules.message.sms.AbstractSmsService;
import com.softtown.modules.message.sms.SmsFactory;
import com.softtown.modules.organization.dao.CompOrgEmplDao;
import com.softtown.modules.organization.dto.*;
import com.softtown.modules.organization.entity.*;
import com.softtown.modules.organization.service.*;
import com.softtown.modules.organization.vo.*;
import com.softtown.modules.oss.cloud.OSSFactory;
import com.softtown.modules.security.user.SecurityUser;
import com.softtown.modules.sys.dto.SysUserDTO;
import com.softtown.modules.sys.entity.*;
import com.softtown.modules.sys.enums.StatusEnum;
import com.softtown.modules.sys.service.*;
import com.softtown.modules.sys.vo.SysUserVO;
import com.softtown.modules.utils.GetFathersIdByDept;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.*;

/**
 * @author: Dingyayong
 * @Date: 2019/6/4 11:03
 * @Description:
 */
@Service
public class CompOrgEmplServiceImpl extends BaseServiceImpl<CompOrgEmplDao, CompOrgEmplEntity> implements CompOrgEmplService {

    @Resource
    private CompSysUserEmplService compSysUserEmplService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private CompSysRoleUserService compSysRoleUserService;

    @Resource
    private CompSysUserApplService compSysUserApplService;

    @Resource
    private CompOrgEmplPosnService compOrgEmplPosnService;

    @Resource
    private CompOrgHstEmplService compOrgHstEmplService;

    @Resource
    private CompOrgDeptService compOrgDeptService;

    @Resource
    private SysEmailService sysEmailService;

    @Resource
    private SysParamsService sysParamsService;

    @Resource
    private SysMsgSendWayService sysMsgSendWayService;

    @Resource
    private SysCompService sysCompService;

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private CompSysParamService compSysParamService;

    @Resource
    private CompSysHstUserEmplService compSysHstUserEmplService;

    private static final String EAMIL = "MAIL_SERVICE_IS_USABLE";

    private static final String SMS = "SMS_SERVICE_IS_USABLE";

    private static final String YES = "Y";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmpl(Long userId, Long compId) {
        CompSysUserEmplEntity compSysUserEmplEntity = compSysUserEmplService
                .findCompEmpl(compId, userId);

        CompSysHstUserEmplEntity compSysHstUserEmplEntity =new CompSysHstUserEmplEntity();
        compSysHstUserEmplEntity.setCompId(compId);
        compSysHstUserEmplEntity.setExprDate(new Date());
        compSysHstUserEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        if(compSysUserEmplEntity.getEmplId() != null){
            compSysHstUserEmplEntity.setEmplIdOld(compSysUserEmplEntity.getEmplId());
        }
        compSysHstUserEmplEntity.setUserId(userId);
        compSysHstUserEmplService.insert(compSysHstUserEmplEntity);
        compSysUserEmplEntity.setIsDeleted(null);
        compSysUserEmplService.updateUserEmpl(compSysUserEmplEntity);
    }

    @Override
    public SysUserVO findEmplUser(Long emplId, Long compId) {
        CompSysUserEmplEntity compSysUserEmplEntity = compSysUserEmplService
                .findEmpl(compId, emplId);
        SysUserEntity sysUserEntity = sysUserService.getByUserId(compSysUserEmplEntity.getUserId());
        return ConvertUtils.sourceToTarget(sysUserEntity, SysUserVO.class);
    }

    @Override
    public List<Long> findEmplUserRole(Long compId, Long userId) {
        return compSysRoleUserService.getRoleIdList(compId, userId);
    }

    @Override
    public CompOrgEmplEntity findById(Long id) {
        return baseDao.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activeOrgEmpl(Long id) {
        CompOrgEmplEntity compOrgEmplEntity = baseDao.getById(id);
        if (compOrgEmplEntity.getStatus().equals(StatusEnum.FORBIDDENSTATUS.value())) {
            compOrgEmplEntity.setStatus(StatusEnum.ACTIVATESTATUS.value());
        } else {
            compOrgEmplEntity.setStatus(StatusEnum.FORBIDDENSTATUS.value());
        }
        compOrgEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        baseDao.updateOrgEmpl(compOrgEmplEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approveUserAppl(SysUserDTO sysUserDTO) {
        SysCompEntity sysCompEntity = sysCompService.getCompanyById(sysUserDTO.getCompId());
        SysUserEntity sysUserEntity1 = sysUserService.getEntityByMobile(sysUserDTO.getMobile());
        if(sysUserDTO.getEmplId() !=null){
            CompSysUserEmplEntity compSysUserEmplEntitys = compSysUserEmplService
                .findEmpl(sysUserDTO.getCompId(), sysUserDTO.getEmplId());
            if (compSysUserEmplEntitys != null) {
                if(compSysUserEmplEntitys.getUserId() !=null){
                    if(!sysUserEntity1.getId().equals(compSysUserEmplEntitys.getUserId())){
                        CompSysHstUserEmplEntity compSysHstUserEmplEntity =new CompSysHstUserEmplEntity();
                        compSysHstUserEmplEntity.setCompId(sysUserDTO.getCompId());
                        compSysHstUserEmplEntity.setExprDate(new Date());
                        compSysHstUserEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                        compSysHstUserEmplEntity.setEmplIdOld(sysUserDTO.getEmplId());
                        compSysHstUserEmplEntity.setUserId(compSysUserEmplEntitys.getUserId());
                        compSysHstUserEmplService.insert(compSysHstUserEmplEntity);
                        compSysUserEmplEntitys.setEmplId(null);
                        compSysUserEmplEntitys.setIsDeleted(IsDeleteEnum.NORMAL.value());
                        compSysUserEmplEntitys.setUpdateDate(new Date());
                        compSysUserEmplEntitys.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                        compSysUserEmplService.updateUserEmpl(compSysUserEmplEntitys);
                        CompSysUserEmplEntity compSysUserEmplEntity = new CompSysUserEmplEntity();
                        compSysUserEmplEntity.setCompId(sysUserDTO.getCompId());
                        compSysUserEmplEntity.setEmplId(sysUserDTO.getEmplId());
                        compSysUserEmplEntity.setUserId(sysUserEntity1.getId());
                        if (compSysUserEmplService.getActiveUser(sysUserDTO.getCompId()) >= sysCompEntity
                            .getActivatableUsers()) {
                            compSysUserEmplEntity.setStatus(StatusEnum.FORBIDDENSTATUS.value());
                        } else {
                            compSysUserEmplEntity.setStatus(StatusEnum.ACTIVATESTATUS.value());
                        }
                        compSysUserEmplService.insert(compSysUserEmplEntity);
                        CompSysHstUserEmplEntity compSysHstUserEmplEntity1 =
                            new CompSysHstUserEmplEntity();
                        compSysHstUserEmplEntity1.setCompId(sysUserDTO.getCompId());
                        compSysHstUserEmplEntity1.setExprDate(new Date());
                        compSysHstUserEmplEntity1.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                        compSysHstUserEmplEntity1.setEmplIdNew(sysUserDTO.getEmplId());
                        compSysHstUserEmplEntity1.setUserId(sysUserEntity1.getId());
                        compSysHstUserEmplService.insert(compSysHstUserEmplEntity1);
                    }
                }else {
                    CompSysHstUserEmplEntity compSysHstUserEmplEntity =new CompSysHstUserEmplEntity();
                    compSysHstUserEmplEntity.setCompId(sysUserDTO.getCompId());
                    compSysHstUserEmplEntity.setExprDate(new Date());
                    compSysHstUserEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                    compSysHstUserEmplEntity.setEmplIdNew(sysUserDTO.getEmplId());
                    compSysHstUserEmplEntity.setUserId(sysUserEntity1.getId());
                    compSysHstUserEmplService.insert(compSysHstUserEmplEntity);
                    compSysUserEmplEntitys.setUserId(sysUserEntity1.getId());
                    compSysUserEmplEntitys.setIsDeleted(IsDeleteEnum.NORMAL.value());
                    compSysUserEmplEntitys.setUpdateDate(new Date());
                    compSysUserEmplEntitys.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                    compSysUserEmplService.updateUserEmpl(compSysUserEmplEntitys);
                }
            } else {
                CompSysHstUserEmplEntity compSysHstUserEmplEntity =new CompSysHstUserEmplEntity();
                compSysHstUserEmplEntity.setCompId(sysUserDTO.getCompId());
                compSysHstUserEmplEntity.setExprDate(new Date());
                compSysHstUserEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                compSysHstUserEmplEntity.setEmplIdNew(sysUserDTO.getEmplId());
                compSysHstUserEmplEntity.setUserId(sysUserEntity1.getId());
                CompSysUserEmplEntity compSysUserEmplEntity = new CompSysUserEmplEntity();
                compSysUserEmplEntity.setCompId(sysUserDTO.getCompId());
                compSysUserEmplEntity.setEmplId(sysUserDTO.getEmplId());
                compSysUserEmplEntity.setUserId(sysUserEntity1.getId());
                if (compSysUserEmplService.getActiveUser(sysUserDTO.getCompId()) >= sysCompEntity
                    .getActivatableUsers()) {
                    compSysUserEmplEntity.setStatus(StatusEnum.FORBIDDENSTATUS.value());
                } else {
                    compSysUserEmplEntity.setStatus(StatusEnum.ACTIVATESTATUS.value());
                }
                compSysUserEmplService.insert(compSysUserEmplEntity);
                compSysHstUserEmplService.insert(compSysHstUserEmplEntity);
            }
        }else {
            CompSysUserEmplEntity compSysUserEmplEntity = new CompSysUserEmplEntity();
            compSysUserEmplEntity.setCompId(sysUserDTO.getCompId());
            compSysUserEmplEntity.setUserId(sysUserEntity1.getId());
            compSysUserEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
            if (compSysUserEmplService.getActiveUser(sysUserDTO.getCompId()) >= sysCompEntity.getActivatableUsers()) {
                compSysUserEmplEntity.setStatus(StatusEnum.FORBIDDENSTATUS.value());
            } else {
                compSysUserEmplEntity.setStatus(StatusEnum.ACTIVATESTATUS.value());
            }
            compSysUserEmplService.insert(compSysUserEmplEntity);
        }

        for (Long roleId : sysUserDTO.getRoleIdList()) {
            CompSysRoleUserEntity compSysRoleUserEntity = new CompSysRoleUserEntity();
            compSysRoleUserEntity.setCompId(sysUserDTO.getCompId());
            compSysRoleUserEntity.setUserId(sysUserEntity1.getId());
            compSysRoleUserEntity.setRoleId(roleId);
            compSysRoleUserService.insert(compSysRoleUserEntity);
        }
        CompSysUserApplEntity compSysUserApplEntity = compSysUserApplService
                .findByUserIdAndCompId(sysUserDTO.getCompId(), sysUserEntity1.getId());
        compSysUserApplEntity.setIsDeleted(null);
        compSysUserApplService.updateComUserAppl(compSysUserApplEntity);
        if (sysUserEntity1.getEmail() != null) {
            String email = sysParamsService.getValue(EAMIL);
            // TODO 多语言
            if (email.equals(YES)) {
                sysEmailService
                        .sendEmailByManager(sysUserEntity1.getEmail(), sysCompEntity.getName(), "同意");
            }
        }
        if (sysUserEntity1.getMobile() != null) {
            String sms = sysParamsService.getValue(SMS);
            if (sms.equals(YES)) {
                SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService
                        .selectBySendTypeAndType(MsgSendWayTypeEnum.
                                SMS.value(), MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
                String smsCode = sysCompEntity.getName() + "|" + "同意";
                //短信服务
                AbstractSmsService service = SmsFactory.build();
                if (service == null) {
                    throw new RenException(ErrorCode.SMS_CONFIG);
                }
                service.sendSmsByLogin(sysUserEntity1.getMobile(),
                        sysMsgSendWayEntity.getMsgTemplateCode(), smsCode);
            }
        }
        SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService
                .selectBySendTypeAndType(MsgSendWayTypeEnum.
                        STTATION_LETTER.value(), MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
        Object[] titleArray = new Object[]{sysCompEntity.getName()};
        String title = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateTitle(), titleArray);
        Object[] contentArray = new Object[]{sysCompEntity.getName(), "同意"};
        String content = MessageFormat
                .format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
        // 发送消息
        Date nowDate = new Date();
        SysMessageEntity sysMessageEntity = new SysMessageEntity();
        sysMessageEntity.setMsgSendWayType(MessageSendWayEnum.APP.value());
        sysMessageEntity.setMsgCompId(sysCompEntity.getId());
        sysMessageEntity.setType(MsgTypeEnum.MANAGER_AGREE_REFUSE.value());
        sysMessageEntity.setCreateDate(nowDate);
        sysMessageEntity.setCreator(SecurityUser.getUser().getId());
        sysMessageEntity.setReceiverId(sysUserEntity1.getId());
        // 0是未读，1是已读
        sysMessageEntity.setIsRead(0);
        sysMessageEntity.setSendDate(nowDate);
        sysMessageEntity.setSenderId(sysCompEntity.getAdminUserId());
        sysMessageEntity.setContent(content);
        sysMessageEntity.setTitle(title);
        sysMessageEntity.setUpdateDate(nowDate);
        sysMessageEntity.setUpdater(SecurityUser.getUser().getId());
        sysMessageEntity.setUpdateTimestamp(Long.toString(System.currentTimeMillis()));
        sysMessageService.insert(sysMessageEntity);
    }

    /**
     * @param @param [compId]
     * @return @return java.util.List<com.softtown.modules.organization.entity.CompOrgEmplEntity>
     * @throws
     * @Title: findByCompId
     * @Description: 根据公司id找信息
     * @author fuming
     * @date 2019/7/6 10:40
     */
    @Override
    public List<CompOrgEmplEntity> findByCompId(Long compId) {
        return baseDao.findByCompId(compId);
    }

    @Override
    public List<CompOrgEmplEntity> findAllCompEmplByBene(Long compId) {
        List<Long> emplIds = baseDao.getEmplListbyBene(compId);
        return baseDao.findByEmplListBene(compId,emplIds);
    }

    /**
     * @param @param [id, compId]
     * @return @return java.util.List<java.lang.Long>
     * @throws
     * @Title: getDeptIdByEmplIdAndCompId
     * @Description: 根据员工ID和公司ID来查找员工表里的部门IDService实现方法
     * @author fuming
     * @date 2019/7/4 17:05
     */
    @Override
    public List<Long> getDeptIdByEmplIdAndCompId(Long id, Long compId) {
        return baseDao.getDeptIdByEmplIdAndCompId(id, compId);
    }

    /**
     * @param @param [compOrgHstEmplDTO]
     * @return @return com.github.pagehelper.PageInfo<com.softtown.modules.organization.entity.CompOrgHstEmplEntity>
     * @throws
     * @Title: getEmplHstListByCompId
     * @Description: 员工履历分页Service实现方法
     * @author fuming
     * @date 2019/7/4 20:19
     */
    @Override
    public PageInfo<CompOrgHstEmplEntity> getEmplHstListByCompId(
            CompOrgHstEmplDTO compOrgHstEmplDTO) {
        Integer pageSize = compOrgHstEmplDTO.getPageSize();
        Integer page = compOrgHstEmplDTO.getPage();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }
        List<CompOrgHstEmplEntity> emplHstListByCompId = baseDao
                .getEmplHstListByCompId(compOrgHstEmplDTO.getCompId());
        return new PageInfo<>(emplHstListByCompId);
    }

    /**
     * @param @param [compOrgEmplDTO]
     * @return @return void
     * @throws
     * @Title: addEmployee
     * @Description: 添加员工Service实现方法
     * @author fuming
     * @date 2019/7/5 22:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmployee(CompOrgEmplDTO compOrgEmplDTO) {
        CompOrgEmplEntity compOrgEmplEntity = ConvertUtils
                .sourceToTarget(compOrgEmplDTO, CompOrgEmplEntity.class);
        compOrgEmplEntity.setEmplNum(compOrgEmplDTO.getEmplNum());
        compOrgEmplEntity.setCompId(compOrgEmplDTO.getCompId());
        compOrgEmplEntity.setRealName(compOrgEmplDTO.getRealName());
        if (compOrgEmplDTO.getHeadUrl() != null) {
            if(compOrgEmplDTO.getHeadUrl().length() > 0){
                compOrgEmplEntity.setHeadUrl(compOrgEmplDTO.getHeadUrl());
            }else {
                compOrgEmplEntity.setHeadUrl(null);
            }

        }else {
            compOrgEmplEntity.setHeadUrl(null);
        }
        compOrgEmplEntity.setGender(compOrgEmplDTO.getGender());
        compOrgEmplEntity.setEmail(compOrgEmplDTO.getEmail());
        compOrgEmplEntity.setMobile(compOrgEmplDTO.getMobile());
        compOrgEmplEntity.setDeptId(compOrgEmplDTO.getDeptId());
        compOrgEmplEntity.setStatus(Status.NORMAL.value());
        compOrgEmplEntity.setRemark(compOrgEmplDTO.getRemark());
        insert(compOrgEmplEntity);
        for (Long posnId : compOrgEmplDTO.getPosnIdList()) {
            CompOrgEmplPosnEntity compOrgEmplPosnEntity = new CompOrgEmplPosnEntity();
            compOrgEmplPosnEntity.setCompId(compOrgEmplDTO.getCompId());
            compOrgEmplPosnEntity.setEmplId(compOrgEmplEntity.getId());
            compOrgEmplPosnEntity.setPosnId(posnId);
            compOrgEmplPosnService.insert(compOrgEmplPosnEntity);
        }
    }

    /**
     * @param @param [compOrgEmplDTO]
     * @return @return void
     * @throws
     * @Title: updateEmplInfos
     * @Description: 员工信息修改Service实现方法
     * @author fuming
     * @date 2019/7/6 9:43
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmplInfos(CompOrgEmplDTO compOrgEmplDTO) {
        Date date = new Date();
        CompOrgEmplEntity byId1 = baseDao.getById(compOrgEmplDTO.getId());
        CompOrgEmplEntity compOrgEmplEntity = ConvertUtils
                .sourceToTarget(compOrgEmplDTO, CompOrgEmplEntity.class);
        compOrgEmplEntity.setId(compOrgEmplDTO.getId());
        compOrgEmplEntity.setEmplNum(compOrgEmplDTO.getEmplNum());
        compOrgEmplEntity.setHeadUrl(compOrgEmplDTO.getHeadUrl());
        compOrgEmplEntity.setRealName(compOrgEmplDTO.getRealName());
        compOrgEmplEntity.setGender(compOrgEmplDTO.getGender());
        compOrgEmplEntity.setEmail(compOrgEmplDTO.getEmail());
        compOrgEmplEntity.setMobile(compOrgEmplDTO.getMobile());
        compOrgEmplEntity.setDeptId(compOrgEmplDTO.getDeptId());
        compOrgEmplEntity.setRemark(compOrgEmplDTO.getRemark());
        compOrgEmplEntity.setUpdater(compOrgEmplDTO.getUpdater());
        compOrgEmplEntity.setUpdateDate(date);
        compOrgEmplEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
        compOrgEmplEntity.setIsDeleted(0);
        baseDao.updateEmplInfos(compOrgEmplEntity);
        if (!byId1.getDeptId().equals(compOrgEmplDTO.getDeptId())) {
            List<CompOrgEmplPosnEntity> listPosnEntity = compOrgEmplPosnService
                    .findListPosnEntity(compOrgEmplDTO.getCompId(), compOrgEmplDTO.getId());
            if (listPosnEntity.isEmpty()) {
                for (Long posnIds : compOrgEmplDTO.getPosnIdList()) {
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity.setCompId(compOrgEmplDTO.getCompId());
                    compOrgEmplPosnEntity.setEmplId(compOrgEmplDTO.getId());
                    compOrgEmplPosnEntity.setPosnId(posnIds);
                    compOrgEmplPosnService.insert(compOrgEmplPosnEntity);
                }
            } else {
                for (CompOrgEmplPosnEntity posnEntity:listPosnEntity) {
                    Long id = posnEntity.getId();
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity1 = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity1.setId(id);
                    compOrgEmplPosnEntity1.setUpdater(compOrgEmplDTO.getUpdater());
                    compOrgEmplPosnEntity1.setUpdateDate(date);
                    compOrgEmplPosnEntity1
                            .setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                    compOrgEmplPosnEntity1.setIsDeleted(null);
                    compOrgEmplPosnService.updateEmplPosn(compOrgEmplPosnEntity1);
                }
                for (Long posnsId : compOrgEmplDTO.getPosnIdList()) {
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity2 = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity2.setCompId(compOrgEmplDTO.getCompId());
                    compOrgEmplPosnEntity2.setEmplId(compOrgEmplDTO.getId());
                    compOrgEmplPosnEntity2.setPosnId(posnsId);
                    compOrgEmplPosnService.insert(compOrgEmplPosnEntity2);
                }
            }
        } else {
            List<CompOrgEmplPosnEntity> listPosnEntity = compOrgEmplPosnService
                    .findListPosnEntity(compOrgEmplDTO.getCompId(), compOrgEmplDTO.getId());
            if (listPosnEntity.isEmpty()) {
                for (Long posnIds : compOrgEmplDTO.getPosnIdList()) {
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity.setCompId(compOrgEmplDTO.getCompId());
                    compOrgEmplPosnEntity.setEmplId(compOrgEmplDTO.getId());
                    compOrgEmplPosnEntity.setPosnId(posnIds);
                    compOrgEmplPosnService.insert(compOrgEmplPosnEntity);
                }
            } else {
                for (CompOrgEmplPosnEntity compOrgEmplPosnEntity:listPosnEntity) {
                    Long id = compOrgEmplPosnEntity.getId();
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity1 = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity1.setId(id);
                    compOrgEmplPosnEntity1.setUpdater(compOrgEmplDTO.getUpdater());
                    compOrgEmplPosnEntity1.setUpdateDate(date);
                    compOrgEmplPosnEntity1
                            .setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
                    compOrgEmplPosnEntity1.setIsDeleted(null);
                    compOrgEmplPosnService.updateEmplPosn(compOrgEmplPosnEntity1);
                }
                for (Long posnsId : compOrgEmplDTO.getPosnIdList()) {
                    CompOrgEmplPosnEntity compOrgEmplPosnEntity2 = new CompOrgEmplPosnEntity();
                    compOrgEmplPosnEntity2.setCompId(compOrgEmplDTO.getCompId());
                    compOrgEmplPosnEntity2.setEmplId(compOrgEmplDTO.getId());
                    compOrgEmplPosnEntity2.setPosnId(posnsId);
                    compOrgEmplPosnService.insert(compOrgEmplPosnEntity2);
                }
            }
        }
    }

    /**
     * @param @param [id]
     * @return @return boolean
     * @throws
     * @Title: deleteEmployee
     * @Description: 员工删除Service实现方法
     * @author fuming
     * @date 2019/7/6 10:08
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmployee(Long id) {
        CompOrgEmplEntity byId = baseDao.getById(id);
        byId.setIsDeleted(null);
        baseDao.updateEmplInfos(byId);
    }

    @Override
    public CompOrgEmplVO getById(Long id) {
        CompOrgEmplEntity byId = baseDao.getById(id);
        return ConvertUtils.sourceToTarget(byId, CompOrgEmplVO.class);
    }

    /**
     * @param @param [compOrgEmplDTO]
     * @return @return com.github.pagehelper.PageInfo<com.softtown.modules.organization.entity.CompOrgEmplEntity>
     * @throws
     * @Title: getEmployeeListByConditions
     * @Description: 员工信息查询和根据条件查询以及多表分页Service实现方法
     * @author fuming
     * @date 2019/7/6 10:20
     */
    @Override
    public PageInfo<CompOrgEmplEntity> getEmployeeListByConditions(CompOrgEmplDTO compOrgEmplDTO) {
        CompSysUserEmplEntity compEmpl = compSysUserEmplService
                .findCompEmpl(compOrgEmplDTO.getCompId(), SecurityUser.getUser().getId());
        Integer page = compOrgEmplDTO.getPage();
        Integer pageSize = compOrgEmplDTO.getPageSize();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }
        List<CompOrgEmplEntity> employeeListByConditions
                = baseDao
                .getEmployeeListByConditions(compOrgEmplDTO.getCompId(), compOrgEmplDTO.getPram(),
                        compEmpl.getEmplId());
        return new PageInfo<>(employeeListByConditions);
    }

    /**
     * 根据公司id和员工id/用户id获取员工信息
     *
     * @param compOrgEmplByCompIdUserIdDTO 员工信息DTO
     * @return com.softtown.common.utils.Result<com.softtown.modules.organization.vo.CompOrgEmplTravelAndStudyVO>
     * @Author fuming
     * @Date 2020/1/20 14:25
     */
    @Override
    public Result<CompOrgEmplTravelAndStudyVO> getEmplToTravlAndStudy(
            CompOrgEmplByCompIdUserIdDTO compOrgEmplByCompIdUserIdDTO) {
        Result result = new Result();
        CompOrgEmplEntity compOrgEmplEntity;
        if (compOrgEmplByCompIdUserIdDTO.getEmplId() != null) {
            // 员工信息
            compOrgEmplEntity = baseDao
                    .selectCompOrgEmplByCompIdAndId(compOrgEmplByCompIdUserIdDTO.getCompId(),
                            compOrgEmplByCompIdUserIdDTO.getEmplId());

        } else {
            // 员工信息
            compOrgEmplEntity = baseDao
                    .selectByCompIdAndUserId(compOrgEmplByCompIdUserIdDTO.getCompId(),
                            compOrgEmplByCompIdUserIdDTO.getUserId());
        }
        if (compOrgEmplEntity != null) {
            // 差旅员工信息VO实例
            CompOrgEmplTravelAndStudyVO compOrgEmplTravelAndStudyVO = new CompOrgEmplTravelAndStudyVO();
            // 部门详细信息
            CompOrgDeptEntity compOrgDeptEntity = compOrgDeptService
                    .getById(compOrgEmplEntity.getDeptId());
            // 当前公司所有的部门
            List<CompOrgDeptEntity> compOrgDeptEntities = compOrgDeptService
                    .getListByCompId(compOrgEmplByCompIdUserIdDTO.getCompId());
            // 获取所在部门的上级
            GetFathersIdByDept getFathersIdByDept = new GetFathersIdByDept();
            QueryWrapper<CompSysParamEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CompSysParamEntity::getCompId,compOrgEmplByCompIdUserIdDTO.getCompId());
            queryWrapper.lambda().eq(CompSysParamEntity::getParamCode,"EXC_BUD_MNG_BY_DEP");
            CompSysParamEntity compSysParamEntity =compSysParamService.getOne(queryWrapper);
            if(compSysParamEntity != null && compSysParamEntity.getParamValue() !=null){
                if(compSysParamEntity.getParamValue().equals(YES)){
                    if (compOrgDeptEntity.getIsBudDept().equals(1)) {
                        compOrgEmplTravelAndStudyVO.setBudDeptId(compOrgDeptEntity.getId());
                        compOrgEmplTravelAndStudyVO.setBudDeptName(compOrgDeptEntity.getName());
                    } else {
                        if (!compOrgDeptEntity.getPid().equals(Long.valueOf(String.valueOf(YesOrNoNumberEnum.NO.value())))){
                            CompOrgDeptEntity compOrgBudgetDeptEntity = getFathersIdByDept
                                    .getBudget(compOrgDeptEntities, compOrgDeptEntity.getPid());
                            if(compOrgBudgetDeptEntity.getId() != null){
                                compOrgEmplTravelAndStudyVO.setBudDeptId(compOrgBudgetDeptEntity.getId());
                                compOrgEmplTravelAndStudyVO.setBudDeptName(compOrgBudgetDeptEntity.getName());
                                // 获取预算部门的上级
                                CompOrgDeptEntity compOrgBudgetDeptEntity1 = compOrgDeptService
                                        .getById(compOrgEmplTravelAndStudyVO.getBudDeptId());
                                Map<String, String> budgetMap = new HashMap<>();
                                budgetMap.put("ids", compOrgBudgetDeptEntity1.getPid().toString());
                                budgetMap.put("pnames", "");
                                budgetMap = getFathersIdByDept
                                        .getIds(compOrgBudgetDeptEntity1.getPid(), compOrgDeptEntities, budgetMap);
                                String budgerPnames = budgetMap.get("pnames");
                                if (!budgerPnames.isEmpty()) {
                                    compOrgEmplTravelAndStudyVO
                                            .setBudDeptPname(budgerPnames.substring(1, budgerPnames.length()));
                                }
                                compOrgEmplTravelAndStudyVO.setBudDeptPid(budgetMap.get("ids"));
                            }
                        }

                    }
                }
            }
            // VO员工详细信息
            compOrgEmplTravelAndStudyVO.setCompOrgEmpl(
                    ConvertUtils.sourceToTarget(compOrgEmplEntity, CompOrgEmplVO.class));
            // 员工id
            compOrgEmplTravelAndStudyVO.setApplEmplId(compOrgEmplEntity.getId());
            // 部门id
            compOrgEmplTravelAndStudyVO.setApplDeptId(compOrgEmplEntity.getDeptId());
            // 部门名称
            compOrgEmplTravelAndStudyVO.setApplDeptName(compOrgDeptEntity.getName());

            Map<String, String> deptMap = new HashMap<>();
            deptMap.put("pnames", "");
            deptMap.put("ids", compOrgDeptEntity.getPid().toString());
            deptMap = getFathersIdByDept
                    .getIds(compOrgDeptEntity.getPid(), compOrgDeptEntities, deptMap);
            String deptPnames = deptMap.get("pnames");
            compOrgEmplTravelAndStudyVO.setApplDeptPids(deptMap.get("ids"));
            if (!deptPnames.isEmpty()) {
                compOrgEmplTravelAndStudyVO
                        .setApplDeptPname(deptPnames.substring(1, deptPnames.length()));
            }
            return result.ok(compOrgEmplTravelAndStudyVO);
        } else {
            return result.error(ErrorCode.UNRELATED_EMPLOYEES_ERROR);
        }

    }

    @Override
    public PageInfo<CompOrgEmplTravelAndStudyVO> getEmplListToTravlAndStudy(
            CompOrgEmplPageByCompIdUserIdDTO compOrgEmplPageByCompIdUserIdDTO) {
        Integer page = compOrgEmplPageByCompIdUserIdDTO.getPage();
        Integer pageSize = compOrgEmplPageByCompIdUserIdDTO.getPageSize();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }
        List<CompOrgEmplTravelAndStudyVO> list = new ArrayList();
        List<CompOrgEmplEntity> orgEmplEntityList = baseDao
                .selectUserIdByCompId(compOrgEmplPageByCompIdUserIdDTO.getCompId());
        for (CompOrgEmplEntity emplEntity:orgEmplEntityList) {
            Long userId = emplEntity.getUserId();
            if (userId != null) {
                //测试
                // 员工信息
                CompOrgEmplEntity compOrgEmplEntity = baseDao
                        .selectEmplListByCompIdAndUserId(compOrgEmplPageByCompIdUserIdDTO.getCompId(),
                                userId, compOrgEmplPageByCompIdUserIdDTO.getPram());
                if (compOrgEmplEntity != null) {
                    //  用户id
                    compOrgEmplEntity.setUserId(userId);
                    // 当前公司所有的部门
                    List<CompOrgDeptEntity> compOrgDeptEntities = compOrgDeptService
                            .getListByCompId(compOrgEmplPageByCompIdUserIdDTO.getCompId());
                    // 差旅员工信息VO实例
                    CompOrgEmplTravelAndStudyVO compOrgEmplTravelAndStudyVO = new CompOrgEmplTravelAndStudyVO();
                    // 部门详细信息
                    CompOrgDeptEntity compOrgDeptEntity = compOrgDeptService
                            .getById(compOrgEmplEntity.getDeptId());
                    // VO员工详细信息
                    compOrgEmplTravelAndStudyVO.setId(compOrgEmplEntity.getId());
                    compOrgEmplTravelAndStudyVO.setCompId(compOrgEmplEntity.getCompId());
                    compOrgEmplTravelAndStudyVO.setEmplNum(compOrgEmplEntity.getEmplNum());
                    compOrgEmplTravelAndStudyVO.setRealName(compOrgEmplEntity.getRealName());
                    compOrgEmplTravelAndStudyVO.setHeadUrl(compOrgEmplEntity.getHeadUrl());
                    compOrgEmplTravelAndStudyVO.setGender(compOrgEmplEntity.getGender());
                    compOrgEmplTravelAndStudyVO.setEmail(compOrgEmplEntity.getEmail());
                    compOrgEmplTravelAndStudyVO.setMobile(compOrgEmplEntity.getMobile());
                    compOrgEmplTravelAndStudyVO.setDeptId(compOrgEmplEntity.getDeptId());
                    compOrgEmplTravelAndStudyVO.setRemark(compOrgEmplEntity.getRemark());
                    compOrgEmplTravelAndStudyVO.setStatus(compOrgEmplEntity.getStatus());
                    compOrgEmplTravelAndStudyVO.setUserId(compOrgEmplEntity.getUserId());
                    // 员工id
                    compOrgEmplTravelAndStudyVO.setApplEmplId(compOrgEmplEntity.getId());
                    // 部门id
                    compOrgEmplTravelAndStudyVO.setApplDeptId(compOrgEmplEntity.getDeptId());
                    // 部门名称
                    compOrgEmplTravelAndStudyVO.setApplDeptName(compOrgDeptEntity.getName());
                    // 获取所在部门的上线
                    GetFathersIdByDept getFathersIdByDept = new GetFathersIdByDept();
                    Map<String, String> deptMap = new HashMap<>();
                    deptMap.put("pnames", "");
                    deptMap.put("ids", compOrgDeptEntity.getPid().toString());
                    deptMap = getFathersIdByDept
                            .getIds(compOrgDeptEntity.getPid(), compOrgDeptEntities, deptMap);
                    String deptPnames = deptMap.get("pnames");
                    compOrgEmplTravelAndStudyVO.setApplDeptPids(deptMap.get("ids"));
                    if (!deptPnames.isEmpty()) {
                        compOrgEmplTravelAndStudyVO
                                .setApplDeptPname(deptPnames.substring(1));
                    }
                    if (compOrgDeptEntity.getIsBudDept().equals(1)) {
                        compOrgEmplTravelAndStudyVO.setBudDeptId(compOrgDeptEntity.getId());
                        compOrgEmplTravelAndStudyVO.setBudDeptName(compOrgDeptEntity.getName());
                    } else {
                        CompOrgDeptEntity compOrgBudgetDeptEntity = getFathersIdByDept
                                .getBudget(compOrgDeptEntities, compOrgDeptEntity.getPid());
                        compOrgEmplTravelAndStudyVO.setBudDeptId(compOrgBudgetDeptEntity.getId());
                        compOrgEmplTravelAndStudyVO
                                .setBudDeptName(compOrgBudgetDeptEntity.getName());
                    }
                    // 获取预算部门的上级
                    CompOrgDeptEntity compOrgBudgetDeptEntity = compOrgDeptService
                            .getById(compOrgEmplTravelAndStudyVO.getBudDeptId());
                    Map<String, String> budgetMap = new HashMap<>();
                    budgetMap.put("ids", compOrgBudgetDeptEntity.getPid().toString());
                    budgetMap.put("pnames", "");
                    budgetMap = getFathersIdByDept
                            .getIds(compOrgBudgetDeptEntity.getPid(), compOrgDeptEntities, budgetMap);
                    String budgerPnames = budgetMap.get("pnames");
                    if (!budgerPnames.isEmpty()) {
                        compOrgEmplTravelAndStudyVO
                                .setBudDeptPname(budgerPnames.substring(1, budgerPnames.length()));
                    }
                    compOrgEmplTravelAndStudyVO.setBudDeptPid(budgetMap.get("ids"));
                    list.add(compOrgEmplTravelAndStudyVO);
                }
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public Result<CompOrgEmplNameVO> getEmplInfoByUserId(CompOrgEmplByCompIdUserIdDTO compOrgEmplByCompIdUserIdDTO) {
        CompOrgEmplEntity compOrgEmplEntity = baseDao.selectByCompIdAndUserId(compOrgEmplByCompIdUserIdDTO.getCompId(), compOrgEmplByCompIdUserIdDTO.getUserId());
        if (compOrgEmplEntity == null) {
            return new Result().error(ErrorCode.UNRELATED_EMPLOYEES_ERROR);
        }
        CompOrgEmplNameVO compOrgEmplNameVO = ConvertUtils.sourceToTarget(compOrgEmplEntity, CompOrgEmplNameVO.class);
        return new Result<CompOrgEmplNameVO>().ok(compOrgEmplNameVO);
    }

    @Override
    public CompOrgEmplEntity getByUserId(Long compId, Long userId) {
        return baseDao.selectByCompIdAndUserId(compId, userId);
    }

    /**
     * 通过公司id和员工id查出员工的部门名称信息
     *
     * @param compId
     * @param id
     * @return java.lang.String
     * @author fuming
     * @date 2019/11/9 17:22
     */
    @Override
    public String selectEmplDeptName(Long compId, Long id) {
        return baseDao.selectEmplDeptName(compId, id);
    }

    /**
     * 查询公司员工信息
     *
     * @param compOrgEmplDTO 公司员工DTO
     * @return com.github.pagehelper.PageInfo<com.softtown.modules.organization.entity.CompOrgEmplEntity>
     * @author fuming
     * @date 2019/11/25 20:02
     */
    @Override
    public PageInfo selectEmployeeList(CompOrgEmplDTO compOrgEmplDTO) {
        Page page = PageHelper.startPage(compOrgEmplDTO.getPage(), compOrgEmplDTO.getPageSize());
        List<CompOrgEmplEntity> compOrgEmplEntities = baseDao
                .selectEmployeeList(compOrgEmplDTO.getCompId(), compOrgEmplDTO.getPram());
        for (CompOrgEmplEntity compOrgEmplEntity : compOrgEmplEntities) {
            if (compOrgEmplEntity.getHeadUrl() != null) {
                compOrgEmplEntity
                        .setHeadUrl(Objects.requireNonNull(OSSFactory.build()).getHeadUrl(compOrgEmplEntity.getHeadUrl()));
            }
            // 获取上级pid(递归)且拼接
            if (compOrgEmplEntity.getDeptId() != null) {
                List<String> fatherDepts = compOrgDeptService
                        .getOrgFatherDepts(compOrgEmplEntity.getDeptId());
                String[] toArray = fatherDepts.toArray(new String[fatherDepts.size()]);
                StringBuilder stringBuilder = new StringBuilder();
                if (toArray.length > 0) {
                    for (String s:toArray) {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append("/").append(s);
                        } else {
                            stringBuilder.append(s);
                        }
                    }
                }
                if (stringBuilder.length() > 0) {
                    compOrgEmplEntity.setDeptName(compOrgEmplEntity.getDeptName().concat("/")
                            .concat(stringBuilder.toString()));
                }
            }
        }
        return ConvertUtils.pageInfoToTarget(page, compOrgEmplEntities);
    }

    /**
     * 根据公司id和员工id查找员工信息
     *
     * @param compId 公司id
     * @param id     员工id
     * @return com.softtown.modules.organization.entity.CompOrgEmplEntity
     * @Author fuming
     * @Date 2020/2/4 11:19
     */
    @Override
    public CompOrgEmplEntity selectCompOrgEmplByCompIdAndId(Long compId, Long id) {
        return baseDao.selectCompOrgEmplByCompIdAndId(compId, id);
    }
}
